#!/bin/bash

source /usr/local/emhttp/plugins/compose.manager/default.cfg
source /boot/config/plugins/compose.manager/compose.manager.cfg

COMPOSE_ROOT=$PROJECTS_FOLDER
COMPOSE_WRAPPER=/usr/local/emhttp/plugins/compose.manager/scripts/compose.sh

sanitize() {
   local s="${1?need a string}"
   s="${s// /_}"
   s="${s/./_}"
   s="${s/-/_}"
   echo "${s,,}" # convert to lowercase
}

recreate=""
if [ "$AUTOSTART_FORCE_RECREATE" = "true" ]; then
    recreate="--recreate"
fi

debug=""
if [ "$DEBUG_TO_LOG" = "true" ]; then
    debug="--debug"
fi

for dir in $COMPOSE_ROOT/*; do
    if [ -d "$dir" ]; then
        if [ -f "$dir/docker-compose.yml" ] || [ -f "$dir/indirect" ]; then
            if [ -f "$dir/autostart" ]; then
                autostart=${dir}/autostart
                if [ 'true' == "$(< "${autostart}" )" ]; then
                    name=${dir}/name
                    name=$(< "${name}")
                    name=$(sanitize ${name})
                    override=""
                    if [ -f "$dir/docker-compose.override.yml" ]; then
                        override="$dir/docker-compose.override.yml"
                        override="-f ${override@Q}"
                    fi
                    envpath=""
                    if [ -f "$dir/envpath" ]; then
                        envpath="$dir/envpath"
                        envpath="$(< "${envpath}" )"
                        envpath="-e ${envpath@Q}"
                    fi
                    logger "Starting compose stack: ${name}"
                    if [ -f "$dir/indirect" ]; then
                        indirect=${dir}/indirect
                        indirect=$(< "${indirect}")
                        eval $COMPOSE_WRAPPER -c up -d ${indirect@Q} -p ${name} $recreate $debug $override $envpath > /dev/null &
                    else
                        dir="$dir/docker-compose.yml"
                        eval $COMPOSE_WRAPPER -c up -f ${dir@Q} -p ${name} $recreate $debug $override $envpath > /dev/null &
                    fi
                fi
            fi
        fi
    fi
done

wait